import React, { Component } from 'react'
import { NavLink } from 'react-router-dom'
import { ArrowRightOutlined, DownOutlined, UpOutlined } from '@ant-design/icons';
import {
  Table,
  Button,
  Row,
  Col,
  Input,
  Empty,
  notification,
  Badge,
  Tabs,
  Descriptions,
  Anchor,
  PageHeader,
  Popover,
  Statistic,
  Tooltip,
} from 'antd';
import Router from 'umi/router';
import { getAlgorithms, getActiveWordvecs } from '@/services/resource';
import { viewVersion, editVersion, modelForecast, queryVersionLog } from '@/services/modelCenter';
import { getDataPurpose } from '@/services/dataCenter';
import {
  getContent, getIndexByContent,
  getKeyWordsTestData,
  getObjectTestData, getTypeById, initTitle, queryIndex, queryLabelContent,
  setHash,
} from '@/pages/algorithmModel/mark/components/config'
import Popconfirm from 'antd/es/popconfirm';
import styles from './style.less'

const { Link } = Anchor;
const { TextArea } = Input;
const font28 = {
  fontSize: 28,
}
const { TabPane } = Tabs;
const colors = ['#ff7100', '#ff9800', '#3bbf45', '#37bc9b', '#1890ff', '#314ed2', '#664be8', '#a94be8',
  '#e84b9c', '#ee4e53', '#b0a4e3', '#ffb61e', '#ffa400', '#fa8c35', '#afdd22', '#e9bb1d', '#e29c45',
  '#ca6924', '#96ce54', '#16a951', '#21a675', '#48c0a3', '#dc3023', '#f36838', '#f9906f', '#1685a9', '#4b5cc4', '#4c8dae'];


function ShowToolTip(str, len = 20) {
  // const str = `${key}: ${val}`
  const currentLength = str.length;
  if (currentLength < len) return str;
  return <Tooltip title={str}>
    {str.slice(0, len)}
  </Tooltip>
}
class ModelTest extends Component {
  constructor(props) {
    super(props);
    const { algorithmId, anotherAlgorithmId } = props.location.query
    this.state = {
      type: props.match.params.type - 0, // 类型 0实体 1关系 2文本分类 3关键词抽取 4属性抽取
      id: props.match.params.id,
      textareaValue: '',
      testResult: [],
      testLoading: false,
      hasTest: false,
      areaDisabled: false,
      data: {}, // 版本信息
      modelStatistic: null,
      algorithmId: algorithmId === 'null' ? '' : algorithmId,
      anotherAlgorithmId: anotherAlgorithmId === 'null' ? '' : anotherAlgorithmId,
      modelConfigList: [],
      anotherModelConfigList: [],
      // 日志
      logList: [],
      // 版本号
      versionName: '',
      // 模型类型
      modelType: null,
      // 模型列表
      modelList: [],
      // 查看 锚点跳转位置
      targetOffset: window.innerHeight / 8,
      // 日志信息
      anotherLogList: [],
      propertyIdArr: [], // 标注文档中的属性UUID
      initTxtArr: [], // 标注后的文档
      relationArr: [], // 已添加的关系
      relations: [], // 关系
      objectLabels: [], // 实体
      drawerSearch: '', // 抽屉搜索内容
      // 实体属性抽取/关系抽取 展开、折叠
      showMore: {},
      entityObj: {},
      propLabels: [], // 实体属性
      drawerSearchProp: '',
      drawerSearchPropRe: '',
      algorithmName: '', // 算法名称
      anotherAlgorithmName: '', // 算法名称
      // 训练日志分页后展示的文本
      showLogList: [],
      pageNum: 0,
      showAnotherList: [],
      anotherPageNum: 0,
      activeLabel: [], // 已激活的文本分类
    };
    this.textListDom = null
    this.addTextListflag = true
    this.anothertextDom = null
    this.anotherListflag = true
  }

  componentDidMount() {
    this.queryData();
    this.queryVersionLog()
  }

  thisIsFunc(initTxtArr, propertyIdArr, objectLabelList, propLabels) {
    // 标注的实体index
    const { entityObj, markType } = this.state
    initTxtArr && initTxtArr.map(item => {
      const arr = item.split('$_#_$')
      const isProp = propertyIdArr && propertyIdArr.length > 0 &&
        propertyIdArr.indexOf(arr[3]) > -1;
      if (isProp) {
        entityObj[arr[3]] = objectLabelList.length + propLabels.findIndex(label => label.labelName === arr[1]);
      } else {
        entityObj[arr[3]] = objectLabelList.findIndex(label => label === arr[1]);
      }
    })
    this.setState({ entityObj })
  }

  // 获取信息
  queryData() {
    let wordvecs = []
    // 获取词向量
    getActiveWordvecs('').then(res => {
      if (res.retCode === '0') wordvecs = res.data
    })
    getDataPurpose({ commonType: 'model_purpose' }).then(rs => {
      if (rs.retCode === '0') {
        const modelTypeList = []
        rs.data.forEach(modelType => {
          modelTypeList[modelType.commonValue - 0] =
            { commonName: modelType.commonName };
        });
        this.setState({ modelList: modelTypeList })
      }
    })
    const { id, algorithmId, anotherAlgorithmId, algorithmName, anotherAlgorithmName } = this.state;

    viewVersion(id).then(res => {
      if (res.retCode === '0') {
        // 模型类型/实体词向量/(关系/属性词向量)/(关系/属性模型配置结果)/实体模型配置结果
        const { modelType, anotherWordvecId, wordvecId, modelConfig, anotherModelConfig, versionName } = res.data.modelVersionVO;
        this.setState({ modelType, data: res.data, versionName })
        const anotherModelConfigCopy = {}
        const modelConfigCopy = {}
        const modelConfigListCopy = [];
        const anotherModelConfigListCopy = [];
        let algorithms = []
        let anotherAlgorithms = []
        Boolean(algorithmId) && getAlgorithms(algorithmId).then(res => {
          if (res.retCode === '0') {
            algorithms = res.data.parameters;
            // algorithmName = res.data.algorithmName
            if (algorithms.length > 0) {
              for (const i in modelConfig) {
                algorithms.forEach(val => {
                  if (i === val.paramName) {
                    modelConfigCopy[val.paramLabel] = modelConfig[i]
                  }
                })
              }
              for (const k in modelConfigCopy) {
                if (modelConfigCopy[k] === 'True' || modelConfigCopy[k] === 'False') {
                  modelConfigListCopy.push({ label: k, val: modelConfigCopy[k] === 'True' ? '是' : '否' })
                } else if (k === '词向量表') {
                  modelConfigListCopy.push({ label: k, val: wordvecs.filter(item => item.wordvecId === modelConfigCopy[k])[0].wordvecName })
                } else {
                  modelConfigListCopy.push({ label: k, val: modelConfigCopy[k] })
                }
              }
              this.setState({ modelConfigList: modelConfigListCopy, algorithmName: res.data.algorithmName })
            }
          }
        })
        Boolean(anotherAlgorithmId) && getAlgorithms(anotherAlgorithmId).then(res => {
          if (res.retCode === '0') {
            anotherAlgorithms = res.data.parameters;
            if (anotherAlgorithms.length > 0) {
              for (const i in anotherModelConfig) {
                anotherAlgorithms.forEach(val => {
                  if (i === val.paramName) {
                    anotherModelConfigCopy[val.paramLabel] = anotherModelConfig[i]
                  }
                })
              }
              for (const k in anotherModelConfigCopy) {
                if (anotherModelConfigCopy[k] === 'True' || anotherModelConfigCopy[k] === 'False') {
                  anotherModelConfigListCopy.push({ label: k, val: anotherModelConfigCopy[k] === 'True' ? '是' : '否' })
                } else if (k === '词向量表') {
                  anotherModelConfigListCopy.push({ label: k, val: wordvecs.filter(item => item.wordvecId === anotherModelConfigCopy[k])[0].wordvecName })
                } else {
                  anotherModelConfigListCopy.push({ label: k, val: anotherModelConfigCopy[k] })
                }
              }
              this.setState({ anotherModelConfigList: anotherModelConfigListCopy, anotherAlgorithmName: res.data.algorithmName })
            }
          }
        })

        let entityDatas;
        let datas;
        if (modelType === 1 || modelType === 4 || modelType === 5) {
          entityDatas = (res.data.modelVersionVO.anotherModelStatistic && JSON.parse(res.data.modelVersionVO.anotherModelStatistic)) || [];
          datas = (res.data.modelVersionVO.modelStatistic && JSON.parse(res.data.modelVersionVO.modelStatistic)) || [];
        } else {
          entityDatas = res.data.modelVersionVO.modelStatistic && JSON.parse(res.data.modelVersionVO.modelStatistic);
        }
        this.setState({ modelStatistic: entityDatas, datas })
      }
    })
  }

  // 查询训练日志
  queryVersionLog = () => {
    const { id, anotherAlgorithmId, pageNum, anotherPageNum } = this.state;
    queryVersionLog(id).then(res => {
      if (res.retCode === '0') {
        this.setState({ logList: res.data, showLogList: res.data.slice(pageNum * 300, (pageNum + 1) * 300) })
      }
    });
    Boolean(anotherAlgorithmId) && queryVersionLog(-id).then(res => {
      if (res.retCode === '0') {
        this.setState({ anotherLogList: res.data, showAnotherList: res.data.slice(anotherPageNum * 300, (anotherPageNum + 1) * 300) })
      }
    });
  }

  onTextareaChange = e => {
    e.preventDefault();
    this.setState({ textareaValue: e.target.value.trim() })
  }

  testValue() {
    const { id, type, textareaValue, data } = this.state;
    const that = this;
    this.setState({ testLoading: true, areaDisabled: true })
    modelForecast({ ...data.modelInfoVO, content: textareaValue, versionId: id }).then(res => {
      if (res.retCode === '0' && res.data !== null) {
        notification.success({
          message: '操作成功',
          key: '操作成功',
          description: '测试完成',
        });
        // eslint-disable-next-line max-len
        this.setState({ testLoading: false, testResult: res.data, hasTest: true, areaDisabled: true })
        // eslint-disable-next-line max-len
        const { initTxt, initTxtArr, relationLabelList, propertyIdArr, relationArr, objectLabelList, dataSetId, labelProcess, segmentNum, isMarked, activeLabel } = res.data;
        // eslint-disable-next-line max-len
        // 获取触发词列表
        const objects = []
        objectLabelList && objectLabelList.forEach(object => {
          if (object.labelType === 0) {
            objects.push(object.labelName)
          }
        })
        this.thisIsFunc(initTxtArr, propertyIdArr, objects, objectLabelList.filter(label => label.labelType === 1))
        const init = (initTxtArr && initTxtArr.length) ? initTxtArr : getContent(initTxt)
        this.setState({
          activeLabel: activeLabel || [],
          needSave: false,
          initTxt,
          dataSetId,
          isMarked,
          propertyIdArr: propertyIdArr || [],
          objectLabels: objectLabelList.filter(label => label.labelType !== 1),
          propLabels: objectLabelList.filter(label => label.labelType === 1),
          initTxtArr: init,
          relations: relationLabelList || [],
          relationArr: relationArr || [],
          process: {
            labelProcess,
            segmentNum,
          },
          objects,
        }, () => {
          this.setState({ testLoading: false });
          // 定时提交
        });
      } if (res.data === null) {
        this.setState({ testLoading: false });
      }
    });
  }

  editValue() {
    this.setState({ areaDisabled: false, hasTest: false })
  }

  clearValue() {
    this.setState({ textareaValue: '', areaDisabled: false, hasTest: false })
  }

  onPublish(versionStatus) {
    const { id, data } = this.state;
    // eslint-disable-next-line max-len
    editVersion({ versionStatus, versionId: id - 0, modelId: data.modelInfoVO.modelId }).then(res => {
      if (res.retCode === '0') {
        notification.success({
          message: '操作成功',
          key: '操作成功',
          description: '发布成功',
        });
        this.queryData();
      }
    })
  }

  showTestResult(type, testResult) {
    if (!(Boolean(testResult) && testResult.length)) {
      return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} style={{ marginTop: 120 }} />;
    }
    const TestColumnsObj = [{
      title: '实体',
      dataIndex: 'word',
      width: 220,
    }, {
      title: '类型',
      dataIndex: 'type',
      width: 80,
    }, {
      title: '来源',
      dataIndex: 'sentence',
    }];

    const TestColumnsRe = [{
      title: '实体1',
      dataIndex: 'e1',
      width: 220,
    }, {
      title: '实体2',
      dataIndex: 'e2',
      width: 220,
    }, {
      title: '关系',
      dataIndex: 'relation_description',
      width: 120,
    }, {
      title: '来源',
      dataIndex: 'sentence',
    }];

    const TestColumnsKey = [{
      title: '关键字',
      dataIndex: 'keyword',
      width: 220,
    }];

    const TestColumnsProp = type === 5 ? [{
      title: type === 5 ? '事件类别标签' : '实体标签',
      dataIndex: 'entityType',
      width: 200,
    }, {
      title: type === 5 ? '事件触发词' : '实体',
      dataIndex: 'entity',
      width: 200,
    }, {
      title: type === 5 ? '事件元素标签' : '属性标签',
      dataIndex: 'propertyType',
      width: 200,
    }, {
      title: type === 5 ? '实体类型' : '属性',
      dataIndex: 'property',
      width: 200,
    }, {
      title: '来源',
      dataIndex: 'sentence',
    }] : [{
      title: '实体',
      dataIndex: 'entity',
      width: 200,
    }, {
      title: '实体标签',
      dataIndex: 'entityType',
      width: 200,
    }, {
      title: '属性',
      dataIndex: 'property',
      width: 200,
    }, {
      title: '属性标签',
      dataIndex: 'propertyType',
      width: 200,
    }, {
      title: '来源',
      dataIndex: 'sentence',
    }];
    let head = [];
    let rs = '';
    switch (type) {
      case 1:
        head = TestColumnsRe;
        rs = testResult;
        break;
      case 2:
        return <div>{testResult.map(val => val.label.map((item, index) => <Badge count={item} key={index} style={{ backgroundColor: 'rgba(78, 161, 223, .1)', color: 'rgba(78, 161, 223, 1)', border: '1px solid rgba(78, 161, 223, .45)', margin: '0 2px', height: 20, lineHeight: '18px' }} />))}</div>;
      case 3:
        head = TestColumnsKey;
        rs = getKeyWordsTestData(testResult);
        break;
      case 4:
        head = TestColumnsProp;
        rs = testResult;
        break;
      case 5:
        head = TestColumnsProp;
        rs = testResult;
        break;
      case 0:
      default:
        rs = getObjectTestData(testResult);
        head = TestColumnsObj;
        break;
    }
    return <Table
      bordered
      size="small"
      columns={head}
      dataSource={rs}
      rowKey={Math.random()}
      pagination={{ pageSize: 5 }}
    />;
  }

  // 删除标注的关系
  deleteRelation(data, startIndex) {
    const { initTxtArr, relationArr } = this.state;
    const fromItemArray = initTxtArr[startIndex].split('$_#_$');
    fromItemArray.map((val, i) => {
      if (val.indexOf(data[2]) !== -1) {
        fromItemArray.splice(i, 1);
      }
    })
    initTxtArr.splice(startIndex, 1, fromItemArray.join('$_#_$'));
    const newArray = relationArr.filter(item => item !== data.join('#_$_#'));
    this.setState({
      needSave: true,
      initTxtArr,
      relationArr: newArray,
    });
  }

  // 关系  展开/收起
  onShowChange = (labelRelationName, flag) => {
    const { showMore } = this.state;
    const showMoreCopy = JSON.parse(JSON.stringify(showMore));

    this.setState({ showMore: { ...showMoreCopy, [labelRelationName]: flag } })
  }


  // 训练日志滚动
  logcontentScroll = (e, type) => {
    const { pageNum, logList, showLogList, anotherPageNum, showAnotherList, anotherLogList } = this.state
    const height = type === 1 ? this.textListDom.clientHeight : this.anothertextDom.clientHeight
    const offsetHieght = height - e.target.scrollTop;
    const flag = type === 1 ? this.addTextListflag : this.anotherListflag
    // if (offsetHieght < 600 && flag) {
    if (flag) {
      const newpageNum = type === 1 ? pageNum+1 : anotherPageNum + 1;
      if (type === 1) {
        this.addTextListflag = false
        this.setState({
          pageNum: newpageNum,
          showLogList: [...showLogList, ...logList.slice(newpageNum * 300, (newpageNum + 1) * 300)],
        }, () => {
          this.addTextListflag = true
        })
      } else {
        this.anotherListflag = false
        this.setState({
          anotherPageNum: newpageNum,
          showAnotherList: [...showAnotherList, ...anotherLogList.slice(newpageNum * 300, (newpageNum + 1) * 300)],
        }, () => {
          this.addTextListflag = true
        })
      }
    }
  }

  render() {
    const { testResult, textareaValue, testLoading, data, type, modelStatistic, hasTest, areaDisabled, datas,
      modelType, modelConfigList, anotherModelConfigList, logList, versionName, modelList, targetOffset, anotherLogList, initTxtArr, objects, id,
      objectLabels, propLabels, propertyIdArr, relationArr, relations, drawerSearch, showMore, entityObj, drawerSearchProp, drawerSearchPropRe,
      algorithmName, anotherAlgorithmName, showLogList, showAnotherList, activeLabel } = this.state;
    const extraModelConfigList = [], extraAnotherModelConfigList = []
    const indexOffset = objectLabels.length;
    for (let i = 0; i < modelConfigList.length % 6; i++) {
      extraModelConfigList.push({})
    }
    for (let i = 0; i < anotherModelConfigList.length % 6; i++) {
      extraAnotherModelConfigList.push({})
    }
    const hasPropSearch = drawerSearchPropRe !== '';
    const isDouble = modelType - 0 === 4 || modelType - 0 === 5;
    const { modelInfoVO, modelVersionVO, dataSetInfoVOS } = data;
    let segmentNum = 0;
    dataSetInfoVOS && dataSetInfoVOS.map(val => {
      segmentNum += val.segmentNum - 0
    });
    const d = (modelStatistic && modelStatistic[0]) || {};
    const obj = (datas && datas[0]) || {};
    const status = data.modelVersionVO && data.modelVersionVO.versionStatus.toString();
    const routes = [
      {
        path: `/algorithm/modelCenter?key=${data.modelInfoVO && data.modelInfoVO.modelId}`,
        breadcrumbName: '模型训练',
      },
      {
        path: '/modelTest/index',
        breadcrumbName: '查看模型',
      },
    ];
    const extra = (<div
      style={{
        display: 'flex',
        width: 'max-content',
        justifyContent: 'flex-end',
      }}
    >
      <Statistic
        title="Status"
        value="Pending"
        style={{
          marginRight: 32,
        }}
      />
      <Statistic title="Price" prefix="$" value={568.08} />
    </div>)
    return (
      <div className={styles.modelBox}
        style={{
          backgroundColor: '#F5F5F5',
          padding: 24,
        }}>
        <section>
          <PageHeader
            ghost={false}
            title={data.modelInfoVO && `${data.modelInfoVO.modelName}.${versionName}`}
            subTitle={Number(status) < 0 ? <Badge status="error" text="训练异常" /> :
              [<Badge color="#1890FF" text="训练完成" />, <Badge color="#29CCB1" text="已发布" />, <Badge color="#FF9800" text="训练中" />][status - 0]}
            breadcrumb={{ routes }}
          >
            <div className="content" style={{ display: 'flex', height: 70 }}>
              <div className="main">
                <Descriptions size="small" column={3}>
                  <Descriptions.Item label="模型类型">{modelList[modelType] && modelList[modelType].commonName}</Descriptions.Item>
                </Descriptions>
              </div>
              <div className="extra" style={{ position: 'absolute', top: 0, right: 12 }}>
                {modelType !==6 ? <div className={styles.cal_box}
                      style={{marginRight: (modelType === 1 || modelType === 4 || modelType === 5) ? 360 : 0}}>
                  <div className={styles.box_top}>
                    {'实体算法'}
                  </div>
                  <div className={styles.align_item}>
                    <span>准确率</span>
                    <span>召回率</span>
                    <span>F1</span>
                  </div>
                  <div className={styles.description}>
                    &nbsp;<strong
                    style={font28}>{String(d.precision) !== 'undefined' ? String(d.precision).slice(0, 4) : '---'}</strong>
                    <div style={{marginTop: -18, width: 1, height: 40, background: '#E9E9E9'}}></div>
                    <strong
                      style={font28}>{String(d.recall) !== 'undefined' ? String(d.recall).slice(0, 4) : '---'}</strong>
                    <div style={{marginTop: -18, width: 1, height: 40, background: '#E9E9E9'}}></div>
                    <strong style={font28}>{String(d.F1) !== 'undefined' ? String(d.F1).slice(0, 4) : '---'}</strong>
                  </div>
                </div> :
                  <div className={styles.cal_box}
                       style={{marginRight: (modelType === 1 || modelType === 4 || modelType === 5) ? 360 : 0,width: 200}}>
                    <div className={styles.box_top}>
                      {'知识表示算法'}
                    </div>
                    <div className={styles.align_item}>
                      <span>hit@10</span>
                    </div>
                    <div className={styles.description}>
                      &nbsp;<strong
                      style={font28}>{String(d['hit@10']) !== 'undefined' ? String(d['hit@10']).slice(0, 4) : '---'}</strong>
                      <div style={{marginTop: -18, width: 1, height: 40, background: '#E9E9E9'}}></div>
                    </div>
                  </div>
                }
                {((modelType === 1 || modelType === 4 || modelType === 5)) ? <span>
                  <div className={styles.cal_box} style={{ borderLeft: '1px solid transparent' }}>
                    <div className={styles.box_top}>{modelType === 1 ? '关系算法 ' : (modelType === 4 ? '属性算法 ' : '事件算法')}</div>
                    <div className={styles.align_item}>
                      <span>准确率</span>
                      <span>召回率</span>
                      <span>F1</span>
                    </div>
                    <div className={styles.description}>
                      &nbsp;<strong style={font28}>{String(obj.precision) !== 'undefined' ? String(obj.precision).slice(0, 4) : '---'}</strong>
                      <div style={{ marginTop: -18, width: 1, height: 40, background: '#E9E9E9' }}></div>
                      &nbsp;<strong style={font28}>{String(obj.recall) !== 'undefined' ? String(obj.recall).slice(0, 4) : '---'}</strong>
                      <div style={{ marginTop: -18, width: 1, height: 40, background: '#E9E9E9' }}></div>
                      &nbsp;<strong style={font28}>{String(obj.F1) !== 'undefined' ? String(obj.F1).slice(0, 4) : '---'}</strong>
                    </div>
                  </div>
                </span> : ''}
              </div>
            </div>
          </PageHeader>
        </section>
        <main>
          <div>
            <Tabs style={{ background: '#fff', margin: 0 }}>
              <TabPane tab="详情" key="1">
                <div style={{ backgroundColor: '#F5F5F5', height: 24 }}></div>
                <div style={{ display: 'flex', background: '#f5f5f5' }}>
                  <div style={{ width: '90%', background: '#fff', marginRight: 24 }}>
                    <div id="basic" style={{ padding: '0px 25px 24px' }}>
                      <div className={styles.view_title}>基础信息</div>
                      <Descriptions column={2}>
                        <Descriptions.Item label="">
                          模型ID：{modelInfoVO && modelInfoVO.modelId}
                          <br />
                          <br />
                          {
                            (modelType - 0 === 4 || modelType - 0 === 1 || modelType - 0 === 5) && '实体算法：'
                          }{
                            (modelType - 0 === 4 || modelType - 0 === 1 || modelType - 0 === 5) && anotherAlgorithmName+" ".replace(/ /g, "\u00a0\u00a0\u00a0")
                          }
                          {modelType - 0 === 5 ? '事件算法：' : modelType - 0 === 4 ? '属性算法：' : modelType - 0 === 1 ? '关系算法：' : modelType - 0 === 6 ? '知识表示算法：' : '实体算法：'}{algorithmName}
                          <br />
                          <br />
                          更新时间：{modelVersionVO && modelVersionVO.createTimeShort}
                        </Descriptions.Item>
                      </Descriptions>

                      <div className={styles.font_attribute}>{modelType === 5 ? '实体算法' : modelType === 2 ? '文本分类算法' : modelType === 3 ? '关键词算法' :  modelType === 6 ? '知识表示算法':'实体算法'}</div>
                      <div style={{ display: 'flex', flexWrap: 'wrap' }}>
                        {
                          (modelType !== 1 && modelType !== 4 && modelType !== 5) ?
                            modelConfigList.map((v, i) => <div className={styles.test}>
                              {
                                ShowToolTip(`${v.label}: ${v.val}`)
                              }
                              {/* <Tooltip title={`${v.label} : ${v.val}`}>
                                {v.label} : {v.val}
                              </Tooltip> */}
                            </div>) :
                            anotherModelConfigList.map((v, i) => <div className={styles.test}>
                              {
                                ShowToolTip(`${v.label}: ${v.val}`)
                              }
                              {/* <Tooltip title={`${v.label} : ${v.val}`}>
                                {v.label} : {v.val}
                              </Tooltip> */}
                            </div>)

                        }
                        {
                          (modelType !== 1 && modelType !== 4 && modelType !== 5 && modelType !==6) ?
                            extraModelConfigList.map(() => <div className={styles.test}></div>) :
                            extraAnotherModelConfigList.map(() => <div className={styles.test}></div>)
                        }

                      </div>
                      {/* <Descriptions column={6}> */}
                      {/*  { */}
                      {/*    (modelType !== 1 && modelType !== 4 && modelType !== 5) ? */}
                      {/*      modelConfigList.map((v, i) => <Descriptions.Item style={{border:'1px solid black'}} key={i} label={v.label}>{v.val}</Descriptions.Item>) : */}
                      {/*      anotherModelConfigList.map((v, i) => <Descriptions.Item style={{border:'1px solid black'}} key={i} label={v.label}>{v.val}</Descriptions.Item>) */}

                      {/*  } */}
                      {/* </Descriptions> */}
                      {(modelType === 1 || modelType === 4 || modelType === 5) && <>
                        <div className={styles.font_attribute}>{modelType === 1 ? '关系算法' : (modelType === 5 ? '事件算法' : '属性算法')}</div>
                        <div style={{ display: 'flex', flexWrap: 'wrap' }}>
                          {
                            modelConfigList.map((v, i) => <div className={styles.test}>
                              {
                                ShowToolTip(`${v.label}: ${v.val}`)
                              }
                              {/* <Tooltip title={`${v.label} : ${v.val}`}>
                                {v.label} : {v.val}
                              </Tooltip> */}
                            </div>)

                          }
                          {
                            extraModelConfigList.map(() => <div className={styles.test}></div>)
                          }
                        </div>
                      </>}
                    </div>
                    <div style={{ backgroundColor: '#F5F5F5', height: 24 }}></div>
                    <div id="training-log" style={{ padding: '0px 24px' }}>
                      <div className={styles.view_title}>训练日志</div>
                      <div className={styles.log_font_attribute}>{modelType === 2 ? '文本分类训练' : modelType === 3 ? '关键词训练' :  modelType === 6 ? '知识表示训练' : '实体训练'}</div>
                      <div onScroll={e => this.logcontentScroll(e, (modelType !== 1 && modelType !== 4 && modelType !== 5) ? 1 : 2)} className={styles.logText}>
                        <div ref={res => this.textListDom = res}>
                          {(modelType !== 1 && modelType !== 4 && modelType !== 5) ? showLogList.map(item => <div>{item}</div>) : showAnotherList.map(item => <div>{item}</div>)}
                        </div>
                      </div>
                      {(modelType === 1 || modelType === 4 || modelType === 5) && <>
                        <div className={styles.log_font_attribute}>{modelType === 1 ? '关系训练' : (modelType === 5 ? '事件训练' : '属性训练')}</div>
                        <div onScroll={e => this.logcontentScroll(e, 1)} className={styles.logText}>
                          <div ref={res => this.anothertextDom = res}>
                            {showLogList.map(item => <div>{item}</div>)}
                          </div>
                        </div>
                      </>}
                    </div>
                  </div>
                  <div style={{ width: '9%' }}>
                    <Anchor targetOffset={targetOffset} onClick={e => e.preventDefault()} style={{ position: 'fixed', top: 310, right: 40, width: 140, height: 200, paddingLeft: 30, paddingTop: 20 }}>
                      <Link href="#basic" title="基础信息" />
                      <Link href="#training-log" title="训练日志" />
                    </Anchor>
                  </div>
                </div>
              </TabPane>
              {status && (status === '0' || status === '1') && modelType !==6 && <TabPane tab="测试" key="2">
                <div style={{ backgroundColor: '#F5F5F5', height: 24 }}></div>
                <section>
                  <Row gutter={16}>
                    <Col span={16}>
                      {!hasTest ? <TextArea disabled={areaDisabled} placeholder="请将测试文本粘贴到此处" className={styles.texts} onChange={this.onTextareaChange} value={textareaValue} />
                        : <div className={styles.texts} id={styles.markcontent}>
                          {/* { */}
                          {/*  // eslint-disable-next-line max-len */}
                          {/*  type === 0 && Boolean(testResult) && testResult.length > 0 ? testResult.map(val => setHash(val)) : textareaValue */}
                          {/* } */}
                          {
                            initTxtArr.map((item, index) => {
                              const boolean = false;
                              if (item.length === 1) { // &#10;换行   &#13;回车
                                if (item == '\n') return <br key={index} />;
                                if (item == ' ') {
                                  return <span key={index} id={index} role={`${boolean ? 'selected'
                                    : 'not-select'}`}>&nbsp;</span>;
                                }
                                return <span key={index} id={index}
                                  role={`${boolean ? 'selected' : 'not-select'}`}>{item}</span>;
                              }
                              let txt = '';
                              const arr = item.split('$_#_$');
                              arr.map((val, j) => {
                                if (j > 3) {
                                  txt += `#${queryIndex(initTxtArr, val.split('#_#')[0])}\n`;
                                }
                              })
                              const span =
                                <span key={index} id={index} role="lables"
                                  className={styles[`kg_keyword${getIndexByContent(objectLabels, propLabels, propertyIdArr, arr) % 28}`]}
                                  data-info={`${arr[0]}`}>
                                  <sub role="lables" data-info={`${arr[0]}`}>#{index} </sub>
                                  {`${arr[0]}`}
                                  <sub role="lables" data-info={`${arr[0]}`}>{`${arr[1]}`}
                                    {modelType - '0' === 5 && objects.indexOf(arr[1]) > -1 && '触发词'}</sub>
                                  {
                                    txt && <strong key={txt}
                                      className={styles.reStrong}
                                    // onClick={this.openDrawer.bind(this, index)}
                                    >{txt}</strong>
                                  }
                                </span>;

                              // if (`${index}` === id && (modelType - 0 === 1 || (isDouble && propertyIdArr.indexOf(arr[3]) === -1))) {
                              return (
                                <span>{txt ? <Popover placement="bottom" content={<div style={{ margin: '3px 0px' }} className={styles.container}>
                                  {initTitle(arr, relationArr).map(item => {
                                    // console.log(item)
                                    return (
                                      <div style={{ display: 'table-row' }}>
                                        <div className={styles.labelItemContents}>
                                          <div className={styles.labelItemContent} style={{ color: "#37BC9B", margin: '2px 0px' }}>{queryLabelContent(initTxtArr,
                                            item.split('#')[0]).length > 30 ? item.split('#')[0].slice(0, 30) + '...' : item.split('#')[0]
                                          }</div></div>
                                        <div className={styles.labelItemContents}><div className={styles.labelItemContent} style={{ backgroundColor: colors[entityObj[item.split('#')[3]] % 28] }}>{
                                          item.split('#')[1].length > 30 ? item.split('#')[1].slice(0, 30) + '...' : item.split('#')[1]
                                        }</div></div>
                                        <ArrowRightOutlined style={{ color: "#29CAAF" }} />
                                        <div className={styles.labelItemContents}><div className={styles.labelItemContent} style={{ backgroundColor: colors[entityObj[item.split('#')[4]] % 28], }}>{
                                          queryLabelContent(initTxtArr, item.split('#')[4]).length > 30 ?
                                            queryLabelContent(initTxtArr, item.split('#')[4]).slice(0, 30) + '...' :
                                            queryLabelContent(initTxtArr, item.split('#')[4])
                                        }</div></div>
                                      </div>
                                    );
                                  })}
                                </div>
                                }

                                >{span}</Popover> : span}</span>
                              );
                              // }
                            })
                          }
                        </div>
                      }
                    </Col>
                    <Col span={8}>
                      <div className={styles.texts} style={{ overflowY: 'auto' }}>
                        {/* { */}
                        {/*  this.showTestResult(type, testResult) */}
                        {/* } */}
                        <Tabs>
                          {(modelType - 0 === 1 || modelType - 0 === 4 || modelType - 0 === 5) &&
                            <TabPane tab={modelType - 0 === 1 ? '关系抽取' : `${modelType - 0 === 4 ? '实体属性抽取' : '事件类型'}`} key="1" className={styles.relationView}>
                              {modelType - 0 === 1 &&
                                relations.map((val, index) => {
                                  let j = 0;
                                  let z = 0;
                                  let fromIndex = objectLabels.findIndex(item => item.labelName === val.labelFromName)
                                  let toIndex = objectLabels.findIndex(item => item.labelName === val.labelToName)
                                  const newrelation =
                                    relationArr.length > 0 ?
                                      relationArr.map((item, i) => {
                                        const relationItem = item.split('#_$_#');
                                        if (relationItem[1] === val.labelRelationName && getTypeById(initTxtArr,
                                          relationItem[0]) === val.labelFromName && getTypeById(initTxtArr,
                                            relationItem[2]) === val.labelToName) {
                                          z++;
                                          return <>
                                            <div key={i} className={styles.item}>
                                              <Tooltip title={'#' + queryIndex(initTxtArr, relationItem[0], true)}>
                                                <span className={styles.ellipsi}>#{queryIndex(initTxtArr,
                                                  relationItem[0], true)}&nbsp;</span>
                                              </Tooltip>
                                              <span><ArrowRightOutlined style={{ color: colors[fromIndex % 28], }} /></span>
                                              <Tooltip title={'#' + queryIndex(initTxtArr, relationItem[2], true)}>
                                                <span className={styles.ellipsi}>#{queryIndex(initTxtArr,
                                                  relationItem[2], true)}&nbsp;</span>
                                              </Tooltip>
                                            </div>
                                          </>;
                                        }
                                        j++;
                                        if (j === relationArr.length) {
                                          return ''
                                        }
                                      }) : []
                                  const newrelationCopy = newrelation.filter(item => item !== undefined && item !== '').slice(0, 2)
                                  return (
                                    <div gutter={8} key={index} className={styles.items}>
                                      <span style={{ fontSize: 12, color: 'rgba(135, 149, 161, 1)' }}>{val.labelRelationName}</span> <span style={{
                                        fontSize: 14,
                                        fontWeight: 700,
                                      }}>&nbsp;&nbsp;<span
                                        className={styles[`kg_keyword${fromIndex % 28}`]}
                                        style={{ margin: '2px 12px', padding: '1px 6px', color: '#fff', borderRadius: 4 }}>{val.labelFromName}</span>
                                        <ArrowRightOutlined
                                          style={{ color: '#FF9933' }}
                                          style={{ color: colors[fromIndex % 28], margin: '0 5px' }} />
                                        <span
                                          className={styles[`kg_keyword${toIndex % 28}`]}
                                          style={{ margin: '2px 12px', padding: '1px 6px', color: '#fff', borderRadius: 4 }}>{val.labelToName}</span>
                                      </span>
                                      {z > 2 && <span className={styles.collapse_button}>
                                        <span key={index} onClick={() => this.onShowChange(val.labelRelationName, true)}
                                          style={{ display: !showMore[val.labelRelationName] ? '' : 'none', cursor: 'pointer' }}>展开<DownOutlined /></span>
                                        <span key={index} onClick={() => this.onShowChange(val.labelRelationName, false)}
                                          style={{ display: showMore[val.labelRelationName] ? '' : 'none', cursor: 'pointer' }}>收起<UpOutlined /></span>
                                      </span>}
                                      {z > 0 ? <div className={styles.relation_card}>{z > 2 && !showMore[val.labelRelationName] ? newrelationCopy : newrelation}</div> :
                                        <div className={styles.empty} />}

                                    </div>
                                  );
                                })
                              }
                              {isDouble &&
                                objectLabels.map((val, index) => {
                                  // ------------用于检索显示优化 进行实体检索和 属性检索 并组合显示
                                  // 是否实体标签未匹配到搜索项
                                  const objectSearched = hasPropSearch && val.labelName.indexOf(drawerSearchPropRe) !== -1;
                                  // 是否没有附属信息 需要隐藏
                                  const needHide = [];
                                  // 是否实体就包含关键词 需要全部显示
                                  const showChild = [];
                                  if (hasPropSearch) {
                                    initTxtArr.forEach((obj, i) => {
                                      let reNum = 0;
                                      const labelItem = obj.split('$_#_$');
                                      if (labelItem[1] === val.labelName && propertyIdArr.indexOf(labelItem[3]) === -1) {
                                        showChild[i] = objectSearched || labelItem[0].indexOf(drawerSearchPropRe) !== -1;
                                        // 不包含关键词 检索属性信息
                                        if (!showChild[i]) {
                                          relationArr.forEach(item => {
                                            const relationItem = item.split('#_$_#');
                                            const propTxt = queryIndex(initTxtArr, relationItem[2], true);
                                            if (relationItem[0] === labelItem[3] && propTxt.indexOf(drawerSearchPropRe) !== -1) {
                                              reNum += 1;
                                            }
                                          })
                                          needHide[i] = reNum === 0;
                                        }
                                      }
                                    })
                                  }
                                  // ----------------end
                                  return (
                                    <div gutter={8} key={index} className={styles.items}>
                                      <Button key={index} id={index} data-text={val.labelName}
                                        size="small"
                                        style={{ margin: '9px 0', padding: '0px 24px' }}
                                        className={styles[`kg_keyword${index % 28}`]}
                                      >
                                        {val.labelName}
                                      </Button>
                                      <div className={styles.labelItem}>
                                        {
                                          initTxtArr.map((obj, i) => {
                                            const labelItem = obj.split('$_#_$');
                                            let reNum = 0;
                                            // eslint-disable-next-line max-len
                                            if (labelItem.length > 1 && labelItem[1] === val.labelName
                                              && propertyIdArr.indexOf(labelItem[3]) === -1) {
                                              const newRelation = relationArr.map((item, reIndex) => {
                                                const relationItem = item.split('#_$_#');
                                                const propTxt = queryIndex(initTxtArr, relationItem[2], true);
                                                const hideMe = hasPropSearch && propTxt.indexOf(drawerSearchPropRe) === -1 && !showChild[i];
                                                if (relationItem[0] === labelItem[3] && !hideMe) {
                                                  reNum++;
                                                  return (
                                                    <div key={`re${reIndex}`} className={styles.item}>
                                                      {modelType - 0 !== 4 &&
                                                        <Tooltip title={relationItem[1]}>
                                                          <div className={styles.ellipsi}>{relationItem[1]}</div>
                                                        </Tooltip>
                                                      }
                                                      <Tooltip title={getTypeById(initTxtArr, relationItem[2])}>
                                                        <span className={styles.ellipsi}>{getTypeById(initTxtArr, relationItem[2])}&nbsp;</span>
                                                      </Tooltip>
                                                      <span><ArrowRightOutlined style={{ color: colors[index % 28], }} /></span>
                                                      <Tooltip title={propTxt}>
                                                        <span className={styles.ellipsi}>#{propTxt}&nbsp;</span>
                                                      </Tooltip>
                                                    </div>
                                                  );
                                                }
                                              })
                                              const newrelationCopy = newRelation.filter(item => item !== undefined && item !== '').slice(0, 2)
                                              return <>
                                                <span key={`obj${i}`}
                                                  style={{ background: '#fff', border: `1px solid ${colors[index % 28]}`, color: colors[index % 28] }}
                                                  data-visible={!showChild[i] && needHide[i] ? 'none' : 'block'} className={styles.elli} >
                                                  #{`${i} ${labelItem[0]}`}&nbsp;&nbsp;
                                                </span>
                                                {reNum > 2 && <span className={styles.collapse_button} style={{ display: 'inline', background: '#fff', border: '0px' }}>
                                                  <span key={index} onClick={() => this.onShowChange(`${i} ${labelItem[0]}`, true)}
                                                    style={{ display: !showMore[`${i} ${labelItem[0]}`] ? '' : 'none', cursor: 'pointer', background: '#fff', border: '0px' }}>展开<DownOutlined /></span>
                                                  <span key={index} onClick={() => this.onShowChange(`${i} ${labelItem[0]}`, false)}
                                                    style={{ display: showMore[`${i} ${labelItem[0]}`] ? '' : 'none', cursor: 'pointer', background: '#fff', border: '0px' }}>收起<UpOutlined /></span>
                                                </span>}
                                                {reNum > 0 ? <div className={styles.relation_card}>{reNum > 2 && !showMore[`${i} ${labelItem[0]}`] ? newrelationCopy : newRelation}</div> :
                                                  <div className={styles.empty} />}
                                                {
                                                  (reNum === 0 && (!hasPropSearch || (hasPropSearch && showChild[i]))) && ''
                                                }
                                              </>;
                                            }
                                          })
                                        }
                                      </div>
                                    </div>
                                  );
                                })
                              }
                            </TabPane>}
                          {modelType - 0 !== 5 && <TabPane
                            tab={(modelType - 0 === 1 || modelType === 4 || modelType === 0) ? '实体抽取' : modelType - 0 === 2 ? '文本分类' : modelType - 0 === 3 ? '关键词抽取' : '实体类型'}
                            key="2" className={styles.relationView}>
                            {
                              objectLabels.map((val, index) => {
                                let j = 0;
                                return <div gutter={8} key={index} className={styles.items}
                                  data-visible={(drawerSearch !== '' && val.labelName.indexOf(
                                    drawerSearch) === -1) ? 'none' : 'block'}>
                                  <Button key={index} id={index} data-text={val.labelName}
                                    size="small"
                                    style={{
                                      margin: '5px 0',
                                      padding: '0px 24px',
                                      opacity: !activeLabel.includes(val.labelName) && modelType - 0 === 2 ? 0.4 : 1
                                    }}
                                    className={styles[`kg_keyword${index % 28}`]}
                                  >
                                    {val.labelName}
                                  </Button>
                                  <div className={styles.labelItem}>
                                    {
                                      initTxtArr.map((item, i) => {
                                        const labelItem = item.split('$_#_$');
                                        if (labelItem.length > 1 && labelItem[1] === val.labelName) {
                                          return <span
                                            key={i}
                                            className={styles.ellipsi}
                                            style={{ display: 'inline-block' }}
                                          >#{`${i} ${labelItem[0]}`}&nbsp;&nbsp;
                                            {/*                <Popconfirm title={modelType - 0 === 5 ? '确定删除触发词？' : '确定删除实体？'} */}
                                            {/*                            arrowPointAtCenter */}
                                            {/*                            onConfirm={this.delInstance.bind(this, i, labelItem[3], labelItem[0])}> */}
                                            {/*  <Icon type="close" /> */}
                                            {/* </Popconfirm> */}
                                          </span>
                                        }
                                        j++;
                                        if (j === initTxtArr.length) {
                                          return <div style={{ height: 30 }} />
                                        }
                                      })
                                    }
                                  </div>
                                </div>
                              })
                            }
                          </TabPane>}
                          {(modelType - 0 === 4 || modelType - 0 === 5) &&
                            <TabPane tab={modelType - 0 === 5 ? '实体类型' : "属性抽取"} key="3" className={styles.relationView}>
                              {/* <Search placeholder={modelType - 0 === 5 ? '元素名' : "属性名"} onSearch={value => this.setState({ drawerSearchProp: value })} */}
                              {/*        style={{ width: 200 }} /> */}
                              {
                                propLabels.map((val, index) => {
                                  let j = 0;
                                  return <div gutter={8} key={index} className={styles.items}
                                    data-visible={(drawerSearchProp !== '' && val.labelName.indexOf(
                                      drawerSearchProp) === -1) ? 'none' : 'block'}>
                                    {/* <h2><Badge color={colors[(index + objectLabels.length) % 28]} text={val.labelName} /></h2> */}
                                    <Button key={index} id={index} data-text={val.labelName}
                                      size="small"
                                      style={{ margin: '5px 0', padding: '0px 24px' }}
                                      className={styles[`kg_keyword${(index + indexOffset) % 28}`]}
                                    >
                                      {val.labelName}
                                    </Button>
                                    <div className={styles.labelItem}>
                                      {
                                        initTxtArr.map((item, i) => {
                                          const labelItem = item.split('$_#_$');
                                          if (labelItem[1] === val.labelName) {
                                            return <span key={i}
                                              style={{ display: 'inline-block' }}
                                              className={styles.ellipsi}>#{`${i} ${labelItem[0]}`}&nbsp;&nbsp;
                                            </span>
                                          }
                                          j++;
                                          if (j === initTxtArr.length) {
                                            return ''
                                          }
                                        })
                                      }
                                    </div>
                                  </div>
                                })
                              }
                            </TabPane>
                          }
                        </Tabs>

                      </div>
                    </Col>
                  </Row>
                </section>
                <div className={styles.bottomBtns}>
                  <Button disabled={!textareaValue} type="primary" size="small" loading={testLoading} onClick={this.testValue.bind(this)} >测试</Button>
                  <Button disabled={!hasTest} size="small" onClick={this.editValue.bind(this)}>编辑</Button>
                  <Button disabled={!textareaValue} size="small" onClick={this.clearValue.bind(this)}>清空</Button>
                </div>
              </TabPane>}
            </Tabs>


          </div>
        </main>
      </div >
    );
  }
}

export default ModelTest
